<template>
  <view class="page">
    <!-- 页面内容区域 -->
    <view class="content">
      <!-- 登录状态检查 -->
      <view v-if="!isLoggedIn" class="login-prompt">
        <view class="prompt-icon">
          <uni-icons type="locked" color="#9CA3AF" :size="48" />
        </view>
        <view class="prompt-title">请先登录</view>
        <view class="prompt-desc">登录后查看您的历史订单</view>
        <button class="login-btn" @click="goToLogin">立即登录</button>
      </view>
      
      <!-- 已登录状态 -->
      <view v-else>
        <!-- 订单列表 -->
        <view class="section">
          <view v-if="orders.length === 0" class="empty-state">
            <view class="empty-icon">
              <uni-icons type="cart" color="#D1D5DB" :size="48" />
            </view>
            <view class="empty-text">暂无订单记录</view>
            <view class="empty-desc">快去<text class="link" @click="goToIndex">首页</text>点餐吧~</view>
          </view>
          
          <view v-else class="order-list">
            <view 
              v-for="order in orders" 
              :key="order._id" 
              class="order-item"
            >
              <!-- 订单编号 -->
              <view class="order-number">
                订单号：{{ order.order_no }}
              </view>
              
              <!-- 订单元信息行 -->
              <view class="order-meta">
                <view class="order-time">{{ formatTime(order.create_date) }}</view>
                <view class="order-status" :class="getStatusClass(order.status)">
                  {{ getStatusText(order.status) }}
                </view>
              </view>
              
              <!-- 菜品 Swiper 轮播 -->
              <view class="dishes-swiper-container">
                <swiper class="dishes-swiper" :indicator-dots="false" :autoplay="false" scroll-x>
                  <swiper-item v-for="(dish, index) in order.dishes" :key="index" class="swiper-item">
                    <view class="dish-card">
                      <view v-if="dish.image" class="dish-card-image">
                        <image :src="dish.image" mode="aspectFill" />
                      </view>
                      <view v-else class="dish-card-placeholder">
                        <text>{{ dish.name }}</text>
                      </view>
                      <view class="dish-card-name">
                        {{ dish.name }}
                      </view>
                    </view>
                  </swiper-item>
                </swiper>
              </view>
              
              <!-- 订单操作按钮 -->
              <view class="order-actions">
                <button v-if="order.status === 3" class="action-btn primary" @click.stop="reorder(order)">
                  再来一单
                </button>
                <button v-if="order.status === 3" class="action-btn secondary" @click.stop="goToRate(order)">
                  {{ order.rating?.rated ? '编辑评价' : '评价' }}
                </button>
                <button v-if="order.status === 0" class="action-btn danger" @click.stop="cancelOrder(order)">
                  取消订单
                </button>
              </view>
              
              <!-- 用户评价显示（已完成订单） -->
              <view v-if="order.status === 3 && order.rating?.rated" class="rating-section">
                <!-- 评价标题栏（可点击展开/折叠） -->
                <view class="rating-header-clickable" @click.stop="toggleRatingExpanded(order._id)">
                  <view class="rating-title-left">
                    <view class="rating-score">
                      <text class="score-number">{{ order.rating.overall_score }}</text>
                      <text class="score-star">★</text>
                    </view>
                    <view class="rating-date">{{ formatTime(order.rating.rated_date) }}</view>
                  </view>
                  <view class="rating-toggle-icon" :class="{ expanded: expandedRatings[order._id] }">
                    ▼
                  </view>
                </view>
                
                <!-- 评价详细内容（展开时显示） -->
                <view v-if="expandedRatings[order._id]" class="rating-content">
                  <!-- 总体评价 -->
                  <view v-if="order.rating.overall_comment" class="overall-comment">
                    {{ order.rating.overall_comment }}
                  </view>
                  
                  <!-- 菜品评价 -->
                  <view v-if="order.rating.dishes && order.rating.dishes.length > 0" class="dishes-rating">
                    <view 
                      v-for="(dishRating, index) in order.rating.dishes" 
                      :key="index"
                      class="dish-rating-item"
                    >
                      <view class="dish-rating-header">
                        <view class="dish-name">{{ dishRating.dish_name }}</view>
                        <view class="dish-score">
                          <text class="score-number">{{ dishRating.score }}</text>
                          <text class="score-star">★</text>
                        </view>
                      </view>
                      <view v-if="dishRating.comment" class="dish-comment">
                        {{ dishRating.comment }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { onShow, onHide } from '@dcloudio/uni-app'
import cart from '@/common/cart.js'
import orderWatch from '@/common/order-watch.js'

const isLoggedIn = ref(false)
const orders = ref([])
const expandedRatings = ref({})
let currentUserId = null

// 检查登录状态
const checkLoginStatus = async () => {
  try {
    const token = uni.getStorageSync('uni_id_token')
    let tokenExpired = 0
    try {
      const info = uniCloud.getCurrentUserInfo()
      tokenExpired = info?.tokenExpired || 0
      currentUserId = info?.uid
    } catch (e) {}
    if (!tokenExpired) {
      tokenExpired = Number(uni.getStorageSync('uni_id_token_expired') || 0)
    }
    const valid = !!token && Number(tokenExpired) > Date.now()
    isLoggedIn.value = valid
    if (valid) {
      loadOrders()
      startOrderWatch()
    }
  } catch (error) {
    isLoggedIn.value = false
  }
}

// 启动订单监听
const startOrderWatch = () => {
  if (!currentUserId) return
  
  if (orderWatch.isOrderWatchActive()) {
    return
  }
  
  orderWatch.startOrderWatch({
    userId: currentUserId,
    role: 'user',
    onOrderCreated: (newOrder) => {
      const exists = orders.value.some(o => o._id === newOrder._id)
      if (!exists) {
        orders.value.unshift(newOrder)
      }
      uni.showToast({
        title: '订单已提交',
        icon: 'success',
        duration: 2000
      })
    },
    onOrderUpdated: (updatedOrder) => {
      const index = orders.value.findIndex(o => o._id === updatedOrder._id)
      if (index !== -1) {
        orders.value[index] = updatedOrder
        const statusText = getStatusText(updatedOrder.status)
        uni.showToast({
          title: `订单${statusText}`,
          icon: 'success',
          duration: 2000
        })
      }
    }
  })
}

// 加载订单数据
const loadOrders = async () => {
  try {
    const res = await uniCloud.callFunction({
      name: 'food-order',
      data: { 
        action: 'get-orders',
        data: {
          page: 1,
          pageSize: 20
        }
      }
    })
    
    if (res.result && res.result.code === 200) {
      let orderList = res.result.data?.list || []
      
      const uniqueMap = new Map()
      orderList.forEach(order => {
        if (!uniqueMap.has(order._id)) {
          uniqueMap.set(order._id, order)
        }
      })
      
      orders.value = Array.from(uniqueMap.values())
    }
  } catch (err) {
    console.error('加载订单失败:', err)
  }
}

// 跳转到登录页
const goToLogin = () => {
  uni.navigateTo({
    url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
  })
}

// 获取订单状态样式
const getStatusClass = (status) => {
  const statusMap = {
    '-1': 'cancelled',
    0: 'pending',
    1: 'accepted',
    2: 'cooking',
    3: 'completed'
  }
  return statusMap[status] || 'pending'
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    '-1': '已取消',
    0: '待处理',
    1: '已接单',
    2: '制作中',
    3: '已完成'
  }
  return statusMap[status] || '未知状态'
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 跳转到菜品详情页
const goToDishDetail = (dish) => {
  uni.navigateTo({
    url: `/pages/dish-detail/dish-detail?id=${dish._id || dish.id}`
  })
}

// 再来一单
const reorder = (order) => {
  if (!order.dishes || order.dishes.length === 0) {
    uni.showToast({
      title: '订单菜品为空',
      icon: 'none'
    })
    return
  }

  let addedCount = 0
  order.dishes.forEach(dish => {
    const dishWithId = {
      ...dish,
      _id: dish.id || dish._id
    }
    const success = cart.addItem(dishWithId, dish.count)
    if (success && Array.isArray(success)) {
      addedCount += dish.count || 1
    }
  })

  if (addedCount > 0) {
    uni.showToast({
      title: `已添加 ${addedCount} 件到购物车`,
      icon: 'success'
    })
    cart.syncTabBadge(2)
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/cart/cart'
      })
    }, 1000)
  } else {
    uni.showToast({
      title: '添加购物车失败',
      icon: 'none'
    })
  }
}

// 取消订单
const cancelOrder = (order) => {
  if (order.status !== 0) {
    uni.showToast({
      title: '只能取消待处理的订单',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '确认取消',
    content: '确定要取消这个订单吗？',
    async success(res) {
      if (res.confirm) {
        try {
          const cancelRes = await uniCloud.callFunction({
            name: 'food-order',
            data: {
              action: 'update-order-status',
              data: {
                orderId: order._id,
                status: -1,
                reason: '用户取消'
              }
            }
          })

          if (cancelRes.result && cancelRes.result.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            setTimeout(() => {
              loadOrders()
            }, 500)
          } else {
            uni.showToast({
              title: cancelRes.result?.message || '取消失败',
              icon: 'none'
            })
          }
        } catch (err) {
          uni.showToast({
            title: '取消订单失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到首页
const goToIndex = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

// 跳转到评价页面
const goToRate = (order) => {
  if (!order || !order._id) {
    uni.showToast({
      title: '订单数据异常',
      icon: 'none'
    })
    return
  }
  
  const url = `/pages/rating/rating?orderId=${encodeURIComponent(order._id)}`
  uni.navigateTo({
    url: url,
    fail: (err) => {
      uni.showToast({
        title: '跳转失败，请重试',
        icon: 'none'
      })
    }
  })
}

// 切换评价展开状态
const toggleRatingExpanded = (orderId) => {
  expandedRatings.value[orderId] = !expandedRatings.value[orderId]
}

onMounted(() => {
  checkLoginStatus()
})

onShow(() => {
  checkLoginStatus()
})

onUnmounted(() => {
  orderWatch.stopOrderWatch()
})
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f8fafc;
  padding-bottom: 32rpx;
}

.content {
  padding: 32rpx;
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 120rpx 32rpx;
  background: #ffffff;
  border-radius: 16rpx;
  margin-top: 32rpx;
}

.prompt-icon {
  margin-bottom: 24rpx;
}

.prompt-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #374151;
  margin-bottom: 16rpx;
}

.prompt-desc {
  font-size: 26rpx;
  color: #6B7280;
  margin-bottom: 48rpx;
}

.login-btn {
  background: #007AFF;
  color: #ffffff;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx 48rpx;
  font-size: 28rpx;
  font-weight: 600;
}

/* 订单列表样式 */
.empty-state {
  text-align: center;
  padding: 120rpx 32rpx;
  background: #ffffff;
  border-radius: 16rpx;
}

.empty-icon {
  margin-bottom: 24rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #374151;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #6B7280;
  
  .link {
    color: #007AFF;
    font-weight: 600;
    text-decoration: underline;
  }
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.order-item {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
}

/* 订单编号 */
.order-number {
  font-size: 26rpx;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12rpx;
}

/* 订单元信息行 */
.order-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.order-time {
  font-size: 24rpx;
  color: #9CA3AF;
}

.order-status {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  
  &.pending {
    background: #FEF3C7;
    color: #92400E;
  }
  
  &.completed {
    background: #D1FAE5;
    color: #065F46;
  }
  
  &.cancelled {
    background: #FEE2E2;
    color: #991B1B;
  }
  
  &.cooking {
    background: #DBEAFE;
    color: #1E40AF;
  }
  
  &.accepted {
    background: #E0E7FF;
    color: #1E40AF;
  }
}

/* Swiper 菜品轮播 */
.dishes-swiper-container {
  width: 100%; /* Ensure the container takes full width */
  overflow-x: auto; /* Allow horizontal scrolling for the swiper */
  -webkit-overflow-scrolling: touch; /* Smooth scrolling on iOS */
  padding-left: 24rpx; /* Add padding to the left of the swiper */
  padding-right: 24rpx; /* Add padding to the right of the swiper */
  margin-left: -24rpx; /* Adjust margin to counteract padding */
  margin-right: -24rpx; /* Adjust margin to counteract padding */
}

.dishes-swiper {
  height: 180rpx;
  margin-bottom: 24rpx;
  border-radius: 0;
  overflow: visible;
  background: transparent;
  /* margin-left: -24rpx; */ /* This margin is now handled by dishes-swiper-container */
  /* margin-right: -24rpx; */ /* This margin is now handled by dishes-swiper-container */
  /* padding-left: 24rpx; */ /* This padding is now handled by dishes-swiper-container */
  /* padding-right: 24rpx; */ /* This padding is now handled by dishes-swiper-container */
}

.swiper-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 160rpx !important;
  height: 180rpx;
  margin-right: 12rpx;
  flex-shrink: 0;
}

.dish-card {
  width: 140rpx;
  height: 160rpx;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  border: 2rpx solid #E5E7EB;
}

.dish-card-image {
  flex: 1;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
  overflow: hidden;
}

.dish-card-image image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-card-placeholder {
  flex: 1;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
  color: #9CA3AF;
  font-size: 20rpx;
  font-weight: 600;
  text-align: center;
  padding: 8rpx;
}

.dish-card-name {
  padding: 8rpx 6rpx;
  text-align: center;
  font-size: 20rpx;
  font-weight: 600;
  color: #374151;
  background: #ffffff;
  border-top: 1rpx solid #E5E7EB;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 订单操作按钮 */
.order-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 12rpx;
  margin-top: 24rpx;
}

.action-btn {
  padding: 16rpx 24rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  font-weight: 600;
  transition: background-color 0.3s ease;
  flex: 1;
  text-align: center;
  border: none;

  &.primary {
    background: #007AFF;
    color: #ffffff;
  }

  &.secondary {
    background: #E0E7FF;
    color: #007AFF;
    border: 1rpx solid #007AFF;
  }

  &.danger {
    background: #FEE2E2;
    color: #991B1B;
    border: 1rpx solid #991B1B;
  }
}

/* 用户评价样式 */
.rating-section {
  margin-top: 24rpx;
  padding-top: 24rpx;
  border-top: 1rpx solid #f0f0f0;
}

.rating-header-clickable {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 0;
  cursor: pointer;
}

.rating-title-left {
  display: flex;
  align-items: baseline;
}

.rating-score {
  display: flex;
  align-items: baseline;
}

.score-number {
  font-size: 36rpx;
  font-weight: 700;
  color: #007AFF;
  margin-right: 8rpx;
}

.score-star {
  font-size: 28rpx;
  color: #FFD700;
}

.rating-date {
  font-size: 24rpx;
  color: #9CA3AF;
  margin-left: 24rpx;
}

.rating-toggle-icon {
  font-size: 28rpx;
  color: #9CA3AF;
  transition: transform 0.3s ease;
}

.rating-toggle-icon.expanded {
  transform: rotate(180deg);
}

.rating-content {
  padding-top: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.overall-comment {
  font-size: 28rpx;
  color: #374151;
  margin-bottom: 24rpx;
  line-height: 1.6;
}

.dishes-rating {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.dish-rating-item {
  background: #f9fafb;
  border-radius: 12rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e5e7eb;
}

.dish-rating-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8rpx;
}

.dish-name {
  font-size: 28rpx;
  color: #374151;
  font-weight: 600;
}

.dish-score {
  display: flex;
  align-items: baseline;
}

.dish-comment {
  font-size: 26rpx;
  color: #6B7280;
  margin-top: 8rpx;
  line-height: 1.5;
}
</style>
